// 图片

import * as Cesium from 'cesium'
// import Tiff from 'tiff.js'
// import { fromUrl, fromUrls, fromArrayBuffer, fromBlob } from 'geotiff'
import { fromArrayBuffer } from 'geotiff'

export default {
  // 加载图片
  async loadImage (viewer, url, options) {
    let points = JSON.parse(options.points)
    let degree = this.getAngle(points[0][0], points[0][1], points[1][0], points[1][1])
    points = points.map(item => {
      return Cesium.Cartesian3.fromDegrees(item[0], item[1], item[2] || 1)
    })
    let entity = viewer.entities.add({
      name: 'image',
      polygon: {
        hierarchy: new Cesium.PolygonHierarchy(points),
        material: url,
        stRotation: Cesium.Math.toRadians(360 - degree)
      }
    })

    return entity
  },
  // 获取角度
  getAngle (lng_a, lat_a, lng_b, lat_b) {
    //以a点为原点建立局部坐标系（东方向为x轴,北方向为y轴,垂直于地面为z轴），得到一个局部坐标到世界坐标转换的变换矩阵
    var localToWorld_Matrix = Cesium.Transforms.eastNorthUpToFixedFrame(new Cesium.Cartesian3.fromDegrees(lng_a, lat_a));
    //求世界坐标到局部坐标的变换矩阵
    var worldToLocal_Matrix = Cesium.Matrix4.inverse(localToWorld_Matrix, new Cesium.Matrix4());    	
    //a点在局部坐标的位置，其实就是局部坐标原点
    var localPosition_A = Cesium.Matrix4.multiplyByPoint(worldToLocal_Matrix, new Cesium.Cartesian3.fromDegrees(lng_a, lat_a), new Cesium.Cartesian3());
    //B点在以A点为原点的局部的坐标位置
    var localPosition_B = Cesium.Matrix4.multiplyByPoint(worldToLocal_Matrix, new Cesium.Cartesian3.fromDegrees(lng_b, lat_b), new Cesium.Cartesian3());
    //弧度
    var angle = Math.atan2((localPosition_B.y-localPosition_A.y), (localPosition_B.x-localPosition_A.x))
    //角度
    var theta = angle*(180/Math.PI);
    if (theta < 0) {
      theta = theta + 360;
    }
    return theta
  },
  // 请求tiff
  async fetchTiff (url) {
    const response = await fetch(url, {
      method: 'GET',
      mode: 'cors', // 这会自动添加必要的CORS头部
    })
    return await response.arrayBuffer()
  },
  // 解析tiff为图片
  async getTiffDataUrlByGeotiff (url) {
    let buffer = await this.fetchTiff(url)
    return this.resolveTiffToDataUrl(buffer)
  },
  // 解析tiff为图片
  // async getTiffDataUrlByTiff (url) {
  //   let buffer = await this.fetchTiff(url)
  //   const tiff = new Tiff({ buffer: buffer })
  //   return tiff.toDataURL()
  // },
  // tiff文件转图片
  // tiffToImageByTiff (file) {
  //   return this.fileToArrayBuffer(file).then(event => {
  //     const buffer = event.target.result
  //     const tiff = new Tiff({ buffer: buffer })
  //     return tiff.toDataURL()
  //   })
  // },
  // tiff文件转图片
  tiffToImageByGeotiff (file) {
    return this.fileToArrayBuffer(file).then(async event => {
      const buffer = event.target.result
      return this.resolveTiffToDataUrl(buffer)
    })
  },
  // 解析tiff
  async resolveTiffToDataUrl (buffer) {
    const tiff = await fromArrayBuffer(buffer)
    let image = await tiff.getImage()
    // let [west, south, east, north] = image.getBoundingBox()
    // const code = image.geoKeys.ProjectedCSTypeGeoKey ||
    //   image.geoKeys.GeographicTypeGeoKey;

    // 读取像素信息
    const [red = [], green = [], blue = []] = await image.readRasters();
    //  const [red = [], green = red, blue = red] = await image.readRasters();
    // 将像素信息写入canvas
    const canvas = document.createElement("canvas");
    let width = image.getWidth();
    let height = image.getHeight();
    canvas.width = width;
    canvas.height = height;
    let ctx = canvas.getContext("2d");
    let imageData = ctx.createImageData(width, height);
    for (var i = 0; i < imageData.data.length / 4; i += 1) {
      imageData.data[i * 4 + 0] = red[i];
      imageData.data[i * 4 + 1] = green[i] || 0;
      imageData.data[i * 4 + 2] = blue[i] || 0;
      imageData.data[i * 4 + 3] = red[i] === 0 ? 0 : 255;
    }
    ctx.putImageData(imageData, 0, 0);

    let dataurl = canvas.toDataURL()
    return dataurl

    // fromUrl(item.image).then(tiff => {
      //   console.log(tiff)
      //   // getImage(tiff)
      // });

      // async function getImage(tiff) {
      //   const image = await tiff.getImage();
      //   let bbox = await image.getBoundingBox();
      //   let data = await image.readRasters({
      //     samples: rgbBands // 波段数量，一个波段：[0]，三个波段：[2,1,0]
      //   });
      //   let base64Image = getBase64Image(data)
      //   addToMapboxgl(base64Image)
      // }
      // function getBase64Image(data) {
      //   let thumbnailPixelHeight = data.height
      //   let thumbnailPixelWidth = data.width
      //   let canvas = document.createElement('canvas')
      //   canvas.width = thumbnailPixelWidth
      //   canvas.height = thumbnailPixelHeight
      //   let ctx = canvas.getContext("2d")
      //   let totalPixelCount = 0
      //   for (let y = 0; y < thumbnailPixelHeight; y++) {
      //     for (let x = 0; x < thumbnailPixelWidth; x++) {
      //       let colour = 'rgb(0, 0, 0, 0)' // let the default be no data (transparent)
      //       // 根据灰度值所在范围渲染颜色
      //       if (data[0][totalPixelCount] > 0) {
      //         if (data[0][totalPixelCount] > 50 && data[0][totalPixelCount] <= 55) {
      //           colour = `rgb(15, 255, 0, 1)`
      //         } else if (data[0][totalPixelCount] > 55 && data[0][totalPixelCount] <= 60) {
      //           colour = `rgb(155, 255, 0, 1)`
      //         } else if (data[0][totalPixelCount] > 60 && data[0][totalPixelCount] <= 65) {
      //           colour = `rgb(255, 255, 0, 1)`
      //         } else {
      //           colour = `rgb(255, 255, 0, 1)`
      //         }
      //       }
      //       ctx.fillStyle = colour
      //       ctx.fillRect(x, y, 1, 1)
      //       totalPixelCount++
      //     }
      //   }
      //   let canvasImage = canvas.toDataURL("image/png")
      //   return canvasImage
      // }
      // // 将图片添加到地图
      // function addToMapboxgl(image) {
      //   console.log(image)
      //   // map.addSource('tiff-source', {
      //   //   "type": "image",
      //   //   "url": image,
      //   //   "coordinates": [
      //   //     [114.425597191307, 38.1091563484708],
      //   //     [114.538187627939, 38.1091563484708],
      //   //     [114.538187627939, 37.9627378349512],
      //   //     [114.425597191307, 37.9627378349512]
      //   //   ]
      //   // });
      //   // map.addLayer({
      //   //   id: 'tiff-layer',
      //   //   'type': 'raster',
      //   //   'source': 'tiff-source',
      //   //   'paint': {
      //   //     'raster-fade-duration': 0
      //   //   }
      //   // });
      // }
  },
  fileToArrayBuffer (file) {
    return new Promise(function(resolve, reject){
      const reader = new FileReader()
      reader.onload = function(event) {
        resolve(event)
      }
      reader.onerror = function(event) {
        reject(event)
      }
      reader.readAsArrayBuffer(file)
    })
  },
  fileToBase64(file) {
    return new Promise((resolve, reject) => {
      const reader = new FileReader()
      reader.readAsDataURL(file)
      reader.onload = () => resolve(reader.result)
      reader.onerror = (error) => reject(error)
    })
  }
}